<?php

namespace App\Http\Services;

use App\Exports\DragonExport;
use App\Http\Repositories\Daos\Drag\DragDao;
use App\Http\Repositories\Daos\Order\OrderDao;
use App\Http\Requests\UserContext;
use App\Http\Traits\Errors;
use App\Http\Traits\GlobalConstant;
use App\Models\ClusterMember;
use App\Models\DragDetail;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\Users;
use App\Util\Helper;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;

class DragService extends BaseService
{
    use Errors;

    protected $dragDao;

    public function __construct(DragDao $dragDao)
    {
        $this->dragDao = $dragDao;
    }

    public function lists(UserContext $userContext)
    {
        $userId    = $userContext->getId();
        $lat       = request('lat') ?? 0;
        $lng       = request('lng') ?? 0;
        $isSub     = request('is_sub') ?? 0;//订阅（结束的不显示）
        $isMyself  = request('is_myself') ?? 0;//我发布的
        $isHot     = request('is_hot') ?? 0;//热度
        $keyWord   = request('key_word') ?? '';//关键字
        $isManage  = request('is_manage') ?? 0;//我管理的（群内管理员）
        $canCopy   = request('copy') ?? 0;//可复制列表
        $near      = request('near') ?? 0;//附近的列表（结束的不显示）
        $clusterId = request('cluster_id') ?? 0;//设置了群组的接龙
        if (!empty($isMyself) || !empty($canCopy)) {
            $condition[] = ['user_id', '=', $userId];
        }
        $page   = request('page') ?? 1;
        $size   = request('size') ?? 3;
        $offset = ($page * $size) - $size;
        $query  = $this->dragDao->getModel()->with(["subscribe" => function ($query) use ($userId) {
            $query->select(['publish_user_id'])->where('user_id', $userId);
        }, "goodsList", "goodsList2", "publishUserInfo"         => function ($query) {
            $query->select(['id', 'nickname', 'avatar']);
        }]);
        if (!empty($keyWord)) {
            $query->whereRaw("(title like ? or description like ? or user_id in (select id from users where nickname like ?) or id in (select drag_id from dragon_detail where title like ?))", ["%{$keyWord}%", "%{$keyWord}%", "%{$keyWord}%", "%{$keyWord}%"]);
        }
        if (!empty($near)) {
            $query->whereRaw("(purchase_status =0 and start_time < ? and end_time > ?)", [time(), time()]);
            if (!empty($lat) || !empty($lng)) {
                $query->having('distance', '<=', 3000);
            }
        }
        //是否订阅
        if ($isSub) {
            $query->whereIn('user_id', function ($q) use ($userId) {
                $q->where('user_id', $userId)->select('publish_user_id')->from('subscribe');
            })->whereRaw("(purchase_status =0 and start_time < ? and end_time > ?)", [time(), time()]);//只显示已订阅团长发布的“未开始”和“正在接龙”的接龙活动，已结束的接龙不显示
        }

        //我管理的
        if ($isManage) {
            $query->whereIn('cluster_id', function ($q) use ($userId) {
                $q->where('user_id', $userId)->where('role', 2)->where('status', 1)->select('cluster_id')->from('cluster_member');
            });
        }
        //群组接龙
        if ($clusterId) {
            $query->where('cluster_id', $clusterId);
        }

        //以下是最终决定怎么查询，因为热度要关联订单，所以有啥条件应该写在这个之前
        //热度
        if ($isHot) {
            $condition[] = ['dragon.status', '=', 1];
            $query->whereRaw("(purchase_status =0 and start_time < ? and end_time > ? and order.status =0 and pay_status =1 and refund_status=0)", [time(), time()]);
            $query->select(DB::raw("dragon.*,COUNT(order.id) AS order_count"))->leftjoin('order', 'order.dragon_id', '=', 'dragon.id')->groupBy('dragon.id')->orderBy('order_count', 'desc');
        } else {
            $condition[] = ['status', '=', 1];
            if (!empty($near)) {
                $query->select(DB::raw("*,(6371 * acos(cos(radians(latitude)) * cos(radians($lat)) * cos(radians(longitude) - radians($lng)) + sin(radians(latitude)) * sin(radians($lat))))*1000 AS distance"));
                $query->orderBy('distance', 'asc')->orderBy('created_at', 'desc')->orderBy('purchase_status', 'asc');
            } else {
                $query->select(DB::raw("*"));
                $query->orderBy('created_at', 'desc');
            }

        }
        $list = $query->where($condition)->limit($size)->offset($offset)->get();
        if (!empty($list)) {
            $orderService = new OrderService(new OrderDao(new Order()));
            foreach ($list as &$item) {
                list($item['status_val'], $item['status_tip']) = GlobalConstant::dragStatusTip($item);
                $item['time_str']  = Helper::pastTime($item['created_at']);
                $item['show_pics'] = GlobalConstant::everyGoodsElement($item->goodsList);
                if (!empty($item->orderList)) {
                    $temp                  = $item->orderList->toArray();
                    $item['serial_number'] = implode('、', array_column($temp, 'dragon_serial'));
                    $orderTemp             = array_column($temp, 'goods_snap');
                    foreach ($orderTemp as $value) {
                        $item['total_num'] += array_sum(array_column($value, 'num'));
                    }
                    list($item['verify_val'], $item['verify_tip']) = GlobalConstant::verifyStatusTip($temp);
                }
                $item['recent_list'] = $orderService->serial($item['id']);//接龙号定时显示
                if ($clusterId) {
                    $item['can_op'] = 0;
                    //核销权限检测
                    if ($item['user_id'] == $userId) {//当前接龙就是当前用户发的
                        $item['can_op'] = 1;
                    }
                    if ($item['cluster_id'] != 0) {//该接龙设置了群组，则群主和管理员皆可核销
                        $item['can_op'] = ClusterMember::checkOpStatus($item['cluster_id'], $userId);
                    }
                }
                $item->start_time_second = strtotime($item->start_time);
                $item->end_time_second   = strtotime($item->end_time);
            }
            unset($item);
        }
        return $list;
    }

    public function myAttempt(UserContext $userContext)
    {
        $userId = $userContext->getId();
        $page   = request('page') ?? 1;
        $size   = request('size') ?? 3;
        $offset = ($page * $size) - $size;
        $query  = $this->dragDao->getModel()->with(["subscribe" => function ($query) use ($userId) {
            $query->select(['publish_user_id'])->where('user_id', $userId);
        }, "goodsList", "goodsList2", "publishUserInfo"         => function ($query) {
            $query->select(['id', 'nickname', 'avatar']);
        }])->with(["orderList" => function ($q) use ($userId) {
            $q->where('user_id', $userId)->where('pay_status', 1)->select(['id', 'dragon_id', 'dragon_serial', 'goods_snap', 'status', 'verify', 'created_at']);
        }]);

        //我参与的要按接龙订单时间近到远
        $condition[] = ['dragon.status', '=', 1];
        $query->select(DB::raw("dragon.*,max(order.created_at) as order_created"))->leftjoin('order', 'order.dragon_id', '=', 'dragon.id')->groupBy('dragon.id')->where('order.user_id', $userId)->where('pay_status', 1)->orderBy('order_created', 'desc');
        $list = $query->where($condition)->limit($size)->offset($offset)->get();
        if (!empty($list)) {
            $orderService = new OrderService(new OrderDao(new Order()));
            foreach ($list as &$item) {
                list($item['status_val'], $item['status_tip']) = GlobalConstant::dragStatusTip($item);
                $item['time_str']  = Helper::pastTime($item['created_at']);
                $item['show_pics'] = GlobalConstant::everyGoodsElement($item->goodsList);
                if (!empty($item->orderList)) {
                    $temp                  = $item->orderList->toArray();
                    $item['serial_number'] = implode('、', array_column($temp, 'dragon_serial'));
                    $orderTemp             = array_column($temp, 'goods_snap');
                    foreach ($orderTemp as $value) {
                        $item['total_num'] += array_sum(array_column($value, 'num'));
                    }
                    list($item['verify_val'], $item['verify_tip']) = GlobalConstant::verifyStatusTip($temp);
                }
                $item['recent_list']     = $orderService->serial($item['id']);//接龙号定时显示
                $item->start_time_second = strtotime($item->start_time);
                $item->end_time_second   = strtotime($item->end_time);
            }
            unset($item);
        }
        return $list;
    }

    public function save(UserContext $userContext)
    {
        $userId     = $userContext->getId();
        $canPublish = $userContext->getCanPublish();
        if ($canPublish != 2) $this->showError('无权限发布接龙');
        $data = request('info') ?? '';
        $id   = $data['id'];
//        if (!empty($id)) {
//            $order = Order::where('dragon_id', $id)->where('pay_status', 1)->where('status', 0)->where('refund_status', 0)->first();
//            if ($order) $this->showError('当前接龙已有用户下单，如需编辑请另开接龙并结束此接龙');
//            $dragInfo = $this->dragDao->getOne(['id' => $id]);
//            if ($dragInfo['purchase_status'] == 1 || strtotime($dragInfo['end_time']) < time()) $this->showError('当前接龙已结束,不可编辑');
//        }
        $validator = Validator::make($data, [
            'title'       => 'required',
            'description' => 'required',
            'address'     => 'required',
            'start_time'  => 'required',
            'end_time'    => 'required',
        ], [
            'title.required'       => '请填写接龙标题',
            'description.required' => '请填写接龙描述',
            'address.required'     => '请选择接龙地址',
            'start_time.required'  => '请选择接龙开始时间',
            'end_time.required'    => '请填写接龙结束时间',
        ]);
        if ($validator->fails()) $this->showError($validator->errors()->first());
        if (strtotime($data['start_time']) > strtotime($data['end_time'])) $this->showError('结束时间小于开始时间');

        $goodsList = $data['goods_list'];
        if (empty($goodsList)) $this->showError('请填写接龙商品');
        if (!self::checkPics($goodsList)) $this->showError('每个商品至少传一张图片');
        unset($data['goods_list']);
        unset($data['single_can']);
        unset($data['start_time_second']);
        unset($data['end_time_second']);
        unset($data['status_tip']);
        unset($data['status_val']);
        unset($data['created_at']);
        unset($data['show_pics']);
        DB::beginTransaction();
        try {
            $goodsList = GlobalConstant::sortGoodsPrice($goodsList);
            if (empty($id)) {
                $exist = $this->dragDao->getOne(['title' => $data['title']]);
                if (!empty($exist)) $this->showError('当前标题已存在');
                $insertData      = [];
                $data['user_id'] = $userId;//新增时才加，编辑的时候可能是管理员（此时不修改user_id）
                unset($data['id']);
                $model = $this->dragDao->save($data);
                $id    = $model->id;
                foreach ($goodsList as $item) {
                    $arr               = [];
                    $arr['drag_id']    = $id;
                    $arr['title']      = $item['title'];
                    $arr['price']      = $item['price'];
                    $arr['store']      = $item['store'];
                    $arr['pics']       = json_encode($item['pics']);
                    $arr['created_at'] = time();
                    $arr['updated_at'] = time();
                    $insertData[]      = $arr;
                }
                DB::table('dragon_detail')->insert($insertData);
            } else {
                $exist = $this->dragDao->getModel()->where('id', '!=', $id)->where('title', $data['title'])->first();
                if (!empty($exist)) $this->showError('当前标题已存在');
                //更新前将所有dragon_detail的数据置为不可用，drag_detail不能直接删除了，否则order_detail里面的drag_detail_id可能找不到
//                DB::table('dragon_detail')->where('drag_id', $id)->delete();
                DB::table('dragon_detail')->where('drag_id', $id)->update(['valid' => 0]);
                //update方法不会触发模型的字段set方法
                $data['start_time'] = strtotime($data['start_time']);
                $data['end_time']   = strtotime($data['end_time']);
                $rel                = $this->dragDao->update($id, $data);
                if (!$rel) $this->showError('接龙数据异常');
                foreach ($goodsList as $item) {
                    if (!empty($item['id'])) {
                        $detail        = DragDetail::where('id', $item['id'])->where('drag_id', $id)->first();
                        $detail->valid = 1;
                        $detail->title = $item['title'];
                        $detail->price = $item['price'];
                        $detail->store = $item['store'];
                        $detail->pics  = $item['pics'];
                        $detail->save();
                    } else {
                        DragDetail::create([
                            'drag_id' => $id,
                            'title'   => $item['title'],
                            'price'   => $item['price'],
                            'store'   => $item['store'],
                            'pics'    => $item['pics']
                        ]);
                    }

                }
            }

            DB::commit();
            return $this->dragDao->getOne(['id' => $id], [], ['id', 'user_id']);

        } catch (\Exception $exception) {
            DB::rollBack();
            Log::error('保存接龙失败' . $exception->getMessage());
            $this->showError($exception->getMessage());
        }

    }

    public function detail(UserContext $userContext)
    {
        $userId = $userContext->getId();
        $id     = request('id') ?? 0;
        $isCopy = request('is_copy') ?? 0;
        $field  = ['id', 'user_id', 'cluster_id', 'title', 'description', 'address', 'can_copy', 'latitude', 'longitude', 'send_msg', 'start_time', 'end_time', 'created_at', 'purchase_status'];
        $detail = $this->dragDao->getModel()->where('id', $id)->first($field);
        if (!empty($detail)) {
            $detail->start_time_second = strtotime($detail->start_time);
            $detail->end_time_second   = strtotime($detail->end_time);
            if ($detail->cluster_id == 0 || $detail->user_id == $userId) {//没有设置群组或者发布人就是当前用户
                $detail->single_can = $detail->user_id == $userId ? 1 : 0;
            } else {
                $detail->single_can = ClusterMember::checkOpStatus($detail->cluster_id, $userId);
            }
            if ($detail->user_id == $userId) {
                $detail->show_verify = 1;//当前用户就是发布者，能看到待核销列
            } else {
                if ($detail->cluster_id == 0) {
                    $detail->show_verify = 0;//没有设置群组且当前用户不是发布者
                } else {
                    $detail->show_verify = ClusterMember::showVerify($detail->cluster_id, $userId);
                }
            }
            list($detail->status_val, $detail->status_tip) = GlobalConstant::dragStatusTip($detail);
            $detailField = ['*'];
            if ($isCopy == 1) {
                $detailField = ['title', 'price', 'store', 'pics'];
            }
            $goodsList         = DragDetail::where('drag_id', $id)->where('valid', 1)->get($detailField)->toArray();
            $detail->show_pics = GlobalConstant::everyGoodsElement($goodsList);
            if ($isCopy == 0) {
                foreach ($goodsList as &$item) {
                    $item['num'] = 0;
                }
                unset($item);
            }
            $detail->goods_list = $goodsList;
        }
        return $detail;
    }

    public function endDrag()
    {
        $id = request('id') ?? 0;
        if (empty($id)) $this->showError('接龙信息异常');
        $detail                  = $this->dragDao->getOne(['id' => $id]);
        $detail->purchase_status = $detail->purchase_status == 1 ? 0 : 1;
        return $detail->save();
    }

    public function shopDragList()
    {
        $userId = request('user') ?? 0;
        $isNow  = request('now') ?? 0;//进行中
        $order  = request('order') ?? 0;//30天热销
        $page   = request('page') ?? 1;
        $size   = request('size') ?? 3;
        $offset = ($page * $size) - $size;
        $field  = ['*'];
        $query  = $this->dragDao->getModel()->with(["subscribe" => function ($query) use ($userId) {
            $query->select(['publish_user_id'])->where('user_id', $userId);
        }, "goodsList", "goodsList2", "publishUserInfo"         => function ($query) {
            $query->select(['id', 'nickname', 'avatar']);
        }]);
        //进行中
        if ($isNow) {
            $query->where('purchase_status', 0)->whereRaw("(start_time < ? and end_time > ?)", [time(), time()]);
        }
        //以下是最终决定怎么查询，因为热度要关联订单，所以有啥条件应该写在这个之前
        //30天热销
        if ($order) {
            $condition[] = ['dragon.user_id', '=', $userId];
            $condition[] = ['dragon.status', '=', 1];
//            $condition[] = ['order.created_at', '>', strtotime("-30 days")];
            $createTime = strtotime("-30 days");
//            $query->select(DB::raw("dragon.*,COUNT(order.id) AS order_count"))->leftjoin('order', 'order.dragon_id', '=', 'dragon.id')->groupBy('dragon.id')->orderBy('order_count', 'desc');
            $query->select(DB::raw("dragon.*,COUNT(CASE WHEN pay_status = 1 and order.status =0 and refund_status=0 and order.created_at > $createTime  THEN 1 ELSE 0 END) AS order_count"))->leftjoin('order', 'order.dragon_id', '=', 'dragon.id')->groupBy('dragon.id')->orderBy('order_count', 'desc');
        } else {
            $condition[] = ['status', '=', 1];
            $condition[] = ['user_id', '=', $userId];
            $query->select(DB::raw("*"))->orderBy('created_at', 'desc');
        }
        $list = $query->where($condition)->limit($size)->offset($offset)->orderBy('created_at', 'desc')->get($field);
        if (!empty($list)) {
            $orderService = new OrderService(new OrderDao(new Order()));
            foreach ($list as &$item) {
                list($item['status_val'], $item['status_tip']) = GlobalConstant::dragStatusTip($item);
                $item['show_pics']   = GlobalConstant::everyGoodsElement($item->goodsList);
                $item['time_str']    = Helper::pastTime($item['created_at']);
                $item['recent_list'] = $orderService->serial($item['id']);//接龙号定时显示
            }
            unset($item);
        }
        return $list;
    }

    public function removeDrag(UserContext $userContext)
    {
        $dragId = request('id') ?? 0;
        $userId = $userContext->getId();
        if (empty($dragId)) $this->showError('请选择要删除的接龙');
        $order = Order::where('dragon_id', $dragId)->where('status', 0)->where('pay_status', 1)->first();
        if (!empty($order)) $this->showError('该接龙有付款订单，不可删除');
        return $this->dragDao->updates(['id' => $dragId, 'user_id' => $userId], ['status' => 0]);
    }

    public function checkHadPay()
    {
        $dragId = request('id') ?? 0;
        if (empty($dragId)) $this->showError('查询接龙异常');
        $dragInfo = $this->dragDao->getOne(['id' => $dragId]);
        if (empty($dragInfo)) $this->showError('接龙不存在');
        if ($dragInfo['purchase_status'] == 1 || strtotime($dragInfo['end_time']) < time()) $this->showError('当前接龙已结束,不可编辑');
        $order = Order::where('dragon_id', $dragId)->where('pay_status', 1)->where('status', 0)->where('refund_status', 0)->first();
        if (!empty($order)) $this->showError('当前接龙已有人付款，不可编辑');
        return true;
    }

    protected static function checkPics($goodsList)
    {
        foreach ($goodsList as $item) {
            $flag = false;
            foreach ($item['pics'] as $value) {
                if ($value['type'] == 1) {
                    $flag = true;
                    break;
                }
            }
            if (!$flag) {
                return false;
            }
        }
        return true;
    }

    public function exportDragon()
    {
        $dragonId = request('dragon_id') ?? 0;
        empty($dragonId) && $this->showError('请选择要导出的接龙');
        $dragonInfo = $this->dragDao->getOne(['id' => $dragonId]);
        empty($dragonInfo) && $this->showError('接龙不存在');
        if ($dragonInfo['status'] == 0) $this->showError('接龙已被删除');
        $firstSheet  = self::getRow1($dragonId);
        $row1        = $firstSheet['header'];
        $data1       = $firstSheet['data'];
        $secondSheet = self::getRow2($dragonId);
        $row2        = $secondSheet['header'];
        $data2       = $secondSheet['data'];
        $thirdSheet  = self::getRow3($dragonId);
        $row3        = $thirdSheet['header'];
        $data3       = $thirdSheet['data'];
        $fileData    = new DragonExport($row1, $data1, $row2, $data2, $row3, $data3);
        Excel::store($fileData, 'report/' . $dragonInfo['title'] . '.xlsx');
        return ['url' => config('app.url') . '/uploads/report/' . $dragonInfo['title'] . '.xlsx', 'name' => $dragonInfo['title'] . '.xlsx'];
    }

    private static function getRow1($dragonId)
    {
        $list = Order::where('status', 0)->where('pay_status', 1)->where('refund_status', 0)->where('dragon_id', $dragonId)
            ->get(['id', 'dragon_id', 'user_id', 'dragon_serial', 'created_at', 'remark', 'verify', 'verify_at', 'total_num', 'price_real'])->toArray();
        //接龙商品
        $dragonGoods = DragDetail::where('drag_id', $dragonId)->get(['id', 'title', 'price'])->toArray();
        if (!empty($list)) {
            foreach ($list as &$item) {
                $item['verify_at']  = $item['verify_at'] == 0 ? '' : date('Y/m/d H:s', $item['verify_at']);
                $item['created_at'] = date('Y/m/d H:i', strtotime($item['created_at']));
                $item['verify']     = $item['verify'] == 1 ? '未核销' : '已核销';
                $userInfo           = Users::where('id', $item['user_id'])->first(['nickname', 'mobile']);
                $item['nickname']   = $userInfo['nickname'];
                $item['mobile']     = $userInfo['mobile'];
                $item['price_real'] = '¥' . $item['price_real'];
                //订单商品
                $goodsList = OrderDetail::where('order_id', $item['id'])->with(['goodsInfo' => function ($query) {
                    $query->select(['id', 'title']);
                }])->get(['dragon_detail_id', 'num'])->toArray();
                if (!empty($dragonGoods)) {
                    for ($i = 0; $i < count($dragonGoods); $i++) {
                        $keyName        = $dragonGoods[$i]['title'] . '/¥' . $dragonGoods[$i]['price'];
                        $item[$keyName] = '';
                        foreach ($goodsList as $value) {
                            if ($value['dragon_detail_id'] == $dragonGoods[$i]['id']) {
                                $item[$keyName] = $value['num'];
                                break;
                            }
                        }
                    }
                }
                unset($item['id']);
                unset($item['user_id']);
                unset($item['dragon_id']);
            }
            unset($item);
        }
        $header      = ['dragon_serial' => '接龙号', 'nickname' => '昵称', 'mobile' => '电话',];
        $goodsHeader = [];
        foreach ($dragonGoods as $val) {
            $row               = $val['title'] . '/¥' . $val['price'];
            $goodsHeader[$row] = $row;
        }
        $header = array_merge($header, $goodsHeader);
        $header = array_merge($header, ['total_num' => '商品总数', 'price_real' => '商品总价', 'remark' => '备注', 'created_at' => '下单时间', 'verify_at' => '核销时间', 'verify' => '订单状态']);
        return ['header' => [$header], 'data' => $list];
    }

    private static function getRow2($dragonId)
    {
        $list = Order::where('status', -1)->where('dragon_id', $dragonId)
            ->get(['id', 'dragon_id', 'user_id', 'dragon_serial', 'created_at', 'remark', 'cancel_at', 'total_num', 'price_real'])->toArray();
        //接龙商品
        $dragonGoods = DragDetail::where('drag_id', $dragonId)->get(['id', 'title', 'price'])->toArray();
        if (!empty($list)) {
            foreach ($list as &$item) {
                $item['cancel_at']  = $item['cancel_at'] == 0 ? '' : date('Y/m/d H:s', $item['cancel_at']);
                $item['created_at'] = date('Y/m/d H:i', strtotime($item['created_at']));
                $item['status']     = '已取消';
                $userInfo           = Users::where('id', $item['user_id'])->first(['nickname', 'mobile']);
                $item['nickname']   = $userInfo['nickname'];
                $item['mobile']     = $userInfo['mobile'];
                $item['price_real'] = '¥' . $item['price_real'];
                //订单商品
                $goodsList = OrderDetail::where('order_id', $item['id'])->with(['goodsInfo' => function ($query) {
                    $query->select(['id', 'title']);
                }])->get(['dragon_detail_id', 'num'])->toArray();
                if (!empty($dragonGoods)) {
                    for ($i = 0; $i < count($dragonGoods); $i++) {
                        $keyName        = $dragonGoods[$i]['title'] . '/¥' . $dragonGoods[$i]['price'];
                        $item[$keyName] = '';
                        foreach ($goodsList as $value) {
                            if ($value['dragon_detail_id'] == $dragonGoods[$i]['id']) {
                                $item[$keyName] = $value['num'];
                                break;
                            }
                        }
                    }
                }
                unset($item['id']);
                unset($item['user_id']);
                unset($item['dragon_id']);
            }
            unset($item);
        }
        $header      = ['dragon_serial' => '接龙号', 'nickname' => '昵称', 'mobile' => '电话',];
        $goodsHeader = [];
        foreach ($dragonGoods as $val) {
            $row               = $val['title'] . '/¥' . $val['price'];
            $goodsHeader[$row] = $row;
        }
        $header = array_merge($header, $goodsHeader);
        $header = array_merge($header, ['total_num' => '商品总数', 'price_real' => '商品总价', 'remark' => '备注', 'created_at' => '下单时间', 'cancel_at' => '取消时间', 'status' => '订单状态']);
        return ['header' => [$header], 'data' => $list];
    }

    private static function getRow3($dragonId)
    {
        $list = DragDetail::where('drag_id', $dragonId)->get(['id', 'title', 'price'])->toArray();
        if (!empty($list)) {
            $sql = "dragon_detail_id,sum(num) as total_num,sum(price*num) as total_price";
            foreach ($list as &$item) {
                $goodsDetailTotal    = OrderDetail::where('dragon_id', $dragonId)->where('dragon_detail_id', $item['id'])->whereIn('order_id', function ($query) use ($dragonId) {
                    $query->where('status', 0)->where('pay_status', 1)->where('refund_status', 0)->select('id')->from('order');
                })->selectRaw($sql)->groupBy('dragon_detail_id')->first();
                $item['total']       = $goodsDetailTotal['total_num'] ?? '';
                $item['price']       = '¥' . $item['price'];
                $item['total_price'] = $goodsDetailTotal['total_price'] ? '¥' . $goodsDetailTotal['total_price'] : '';
                unset($item['id']);
            }
            unset($item);
        }
        $header = ['title' => '商品名称', 'price' => '商品价格', 'total' => '商品总数', 'total_price' => '商品总价'];
        return ['header' => [$header], 'data' => $list];
    }

}
